// 图标选择弹窗组件：显示图标选项卡并在选择时回调父组件
import React, { useEffect, useRef, useState } from 'react'
import { View, Text, Button, Image } from '@tarojs/components'
import './IconPicker.less'

type Props = {
  visible: boolean
  categories: Record<string, string[]>
  activeTab: string
  onChangeTab: (tab: string) => void
  onSelectIcon: (url: string) => void
  onClose: () => void
  onCropAction?: () => void
}

const IconPicker: React.FC<Props> = ({ visible, categories, activeTab, onChangeTab, onSelectIcon, onClose, onCropAction }) => {
  // containerRef: 指向选项卡容器，用于计算子 tab 的相对位置并确保其可见
  const containerRef = useRef<any>(null)
  // tabRefs: 存放每个 tab 的 DOM 引用，便于计算指示条位置和滚动对齐
  const tabRefs = useRef<Record<string, any>>({})
  // indicator: 控制选项卡下方滑动指示条的位置、宽度与显示状态
  const [indicator, setIndicator] = useState({ left: 0, width: 0, visible: false })

  useEffect(() => {
    if (!visible) return

    // update: 计算当前激活 tab 的位置并移动指示条，同时尝试滚动使该 tab 居中
    const update = () => {
      const el = tabRefs.current[activeTab]
      const container = containerRef.current
      if (el && container && typeof el.offsetLeft === 'number' && typeof el.offsetWidth === 'number') {
        // 为了视觉效果，限制指示条最大宽度，使其在宽 tab 上居中而不是充满整个 tab
        const naturalWidth = el.offsetWidth
        const maxIndicatorWidth = 36
        const width = Math.min(naturalWidth, maxIndicatorWidth)
        // left 计算为相对容器的偏移并居中到 tab 的中间位置
        const left = (el.offsetLeft - (container.offsetLeft || 0)) + (naturalWidth - width) / 2
        setIndicator({ left, width, visible: true })

        // 尝试调用 DOM scrollIntoView 使激活 tab 可见（兼容 web 环境）
        try {
          if (typeof el.scrollIntoView === 'function') {
            el.scrollIntoView({ behavior: 'smooth', inline: 'center', block: 'nearest' } as any)
          }
        } catch (e) {
          // 某些小程序环境可能不支持 scrollIntoView，忽略异常
        }
      } else {
        // 找不到元素或属性不完整时隐藏指示条
        setIndicator({ left: 0, width: 0, visible: false })
      }
    }

    // 首次运行一次计算，并在窗口大小改变时重新计算以保持对齐
    update()
    window.addEventListener('resize', update)
    return () => window.removeEventListener('resize', update)
  }, [activeTab, visible, categories])

  if (!visible) return null
  return (
    <View className='icon-picker'>
      <View className='icon-picker-mask' onClick={onClose}>
        <View className='icon-picker-center' onClick={e => e.stopPropagation && e.stopPropagation()}>
          <View className='icon-picker-header'>
            <Text className='icon-picker-title'>选择图标</Text>
            <View className='icon-close' onClick={onClose}>×</View>
          </View>
          <View className='icon-tabs' ref={containerRef}>
            {Object.keys(categories).map(tab => (
              <View
                key={tab}
                ref={el => { tabRefs.current[tab] = el }}
                className={`tool-btn ${activeTab === tab ? 'active' : ''}`}
                onClick={() => onChangeTab(tab)}
              >
                {tab}
              </View>
            ))}

            <View
              className='tab-indicator'
              style={{
                left: `${indicator.left}px`,
                width: `${indicator.width}px`,
                opacity: indicator.visible ? 1 : 0
              }}
            />
          </View>
        <View className='icon-picker-grid'>
          {/* 抠图按钮，调用父组件剪裁动作（仅触发 UI 流程） */}
          <View className='icon-picker-action-row'>
            <Button className='crop-action-btn' onClick={() => { onClose(); onCropAction && onCropAction() }}>抠图</Button>
          </View>
          {categories[activeTab].map(url => (
            <View key={url} className='icon-thumb' onClick={() => onSelectIcon(url)}>
              <Image src={url} style={{ width: '100%', height: '100%' }} />
            </View>
          ))}
        </View>
        </View>
      </View>
    </View>
  )
}

export default IconPicker


